package com.helloapp.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.helloapp.dao.UserDao;
import com.helloapp.entity.User;
import com.helloapp.util.JdbcUtil;

public class UserDaoImpl implements UserDao {

	@Override
	public User getByUsernameAndPassword(String username, String password) {
		User user = null;
		try {
			Connection conn = JdbcUtil.getConnection();
			String sql = "select * from user where username =? and password =? ";
			// 3. 创建Statement
			PreparedStatement stm = conn.prepareStatement(sql);
			stm.setString(1, username);
			stm.setString(2, password);
			// 4. 执行SQL语句
			ResultSet res = stm.executeQuery();
			// 5. 处理结果
			String name = null;
			String pwd = null;
			while (res.next()) {
				int id = res.getInt("id");
				name = res.getString("username");
				pwd = res.getString("password");
				user = new User(id,name,pwd);
				break;
			}
	
			JdbcUtil.free(res, stm, conn);
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return user;
	}

	@Override
	public void insert(String username, String password) {
		try {
			Connection conn = JdbcUtil.getConnection();
			String sql = "insert into  user(username,password) values(?,?) ";
			// 3. 创建Statement
			PreparedStatement stm = conn.prepareStatement(sql);
			stm.setString(1, username);
			stm.setString(2, password);
			// 4. 执行SQL语句
			int res = stm.executeUpdate();
			
			JdbcUtil.free(null, stm, conn);
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void add(User user) {
		try {
			Connection conn = JdbcUtil.getConnection();
			String sql = "insert into  user(username,password) values(?,?) ";
			// 3. 创建Statement
			PreparedStatement stm = conn.prepareStatement(sql);
			stm.setString(1, user.getUsername());
			stm.setString(2, user.getPassword());
			// 4. 执行SQL语句
			int res = stm.executeUpdate();
			
			JdbcUtil.free(null, stm, conn);
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
